import KoaRouter from 'koa-router'
// 这样代码才有智能提示
import { Context, Next } from 'koa'
import RoleModel from '../models/Role' //班级管理服务
import { Role } from '../types'
import moment from 'moment'

const router = new KoaRouter()
router.prefix('/api/role')

router.get('/list', async (ctx: Context, next: Next) => {
  ctx.body = {
    code: 200,
    message: '访问成功了0',
    data: await RoleModel.findAll()
  }
})

router.post('/add', async (ctx: Context, next: Next) => {
  const role: Role = ctx.request.body
  role.ctime = moment().format('YYYY-MM-DD HH:mm:ss')
  role.mtime = moment().format('YYYY-MM-DD HH:mm:ss')
  ctx.body = {
    code: 200,
    message: '新增成功',
    data: await RoleModel.create(role)
  }
})

router.put('/update', async (ctx: Context, next: Next) => {
  const role: Role = ctx.request.body
  role.mtime = moment().format('YYYY-MM-DD HH:mm:ss')
  ctx.body = {
    code: 200,
    message: '更新成功',
    data: await RoleModel.update(role, {
      where: {
        id: role.id
      }
    })
  }
})

// 获取path参数即/detail/1，使用ctx.params.名称
// 获取query参数即/detail?limit=10，使用ctx.query.limit
router.get('/detail/:id', async (ctx: Context, next: Next) => {
  ctx.body = {
    code: 200,
    message: '获取成功',
    data: await RoleModel.findOne({
      where: {
        id: ctx.params.id
      }
    })
  }
})

router.delete('/deleteById/:id', async (ctx: Context, next: Next) => {
  ctx.body = {
    code: 200,
    message: '删除成功',
    data: await RoleModel.destroy({
      where: {
        id: ctx.params.id
      }
    })
  }
})

export default router